package wsz.config;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import wsz.mapper.SqlCommandType;
import wsz.pojo.Configuration;
import wsz.pojo.MappedStatement;

import java.io.InputStream;
import java.util.List;
import java.util.Locale;

/**
 * 解析mapper.xml文件
 * @author wsz
 * @date 2021/10/1 1:06
 **/
public class XmlMapperBuilder {

    private Configuration configuration;

    public XmlMapperBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    public void parseMapper(InputStream is) throws DocumentException {
        Document document = new SAXReader().read(is);

        Element rootElement = document.getRootElement();
        String namespace = rootElement.attributeValue("namespace");

        // TODO mapper中的所有待处理节点
        List<Element> selectList = rootElement.selectNodes("//insert");
        selectList.addAll(rootElement.selectNodes("//select"));
        selectList.addAll(rootElement.selectNodes("//update"));
        selectList.addAll(rootElement.selectNodes("//delete"));

        for (Element el: selectList) {
            String id = el.attributeValue("id");
            String resultType = el.attributeValue("resultType");
            String paramterType = el.attributeValue("paramterType");
            String sqlText = el.getTextTrim();

            MappedStatement statement = new MappedStatement();
            statement.setId(id);
            // TODO 判断当前sql类型
            statement.setSqlCommandType(getType(el.getName()));
            statement.setResultType(resultType);
            statement.setParamterType(paramterType);
            statement.setSql(sqlText);

            configuration.getStatementMap().put(namespace + "." + id, statement);
        }

        try {
            // TODO mapper的namespace注册
            configuration.addMapper(Class.forName(namespace));
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    private SqlCommandType getType (String nodeName) {
        return  SqlCommandType.valueOf(nodeName.toUpperCase(Locale.ENGLISH));
    }


}
